//
//  QPJHCountdown.m
//  QPJHLightSDK
//
//  Created by qply on 2020/7/29.
//  Copyright © 2020 Vanney. All rights reserved.
//

#import "QPJHCountdown.h"

#define kUpdateTime 1

@interface QPJHCountdown ()

@property (nonatomic, strong) dispatch_queue_t queue;

@end

@implementation QPJHCountdown


+ (instancetype)shareInstance {
    static QPJHCountdown *countdownInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        countdownInstance = [[QPJHCountdown alloc] init];
    });
    return countdownInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        dispatch_queue_attr_t attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_CONCURRENT, QOS_CLASS_USER_INITIATED, 0);
        dispatch_queue_t queue = dispatch_queue_create("com.QPJHCountdown.queue", attr);
        _queue = queue;
        _timerDictionary = [NSMutableDictionary new];
    }
    return self;
}

///**
// *  倒计时器
// *
// *  @param time     传入需倒计时的时间
// *  @param progress 此处根据传回来的time,更新倒计时的UI
// *  @param finish   计时完成后的回调
// *  @param timeKey  timer的名称，作为唯一标识
// */
- (void)time:(NSTimeInterval)time timeDown:(progressCall)progress finish:(finishCall)finish timeKey:(NSString *)timeKey {
    [self countdown:time updateTime:kUpdateTime progress:progress finish:finish timeKey:timeKey];
}
- (void)time:(NSTimeInterval)time updateTime:(double)updateTime timeDown:(progressCall)progress finish:(finishCall)finish timeKey:(NSString *)timeKey {
    [self countdown:time updateTime:updateTime progress:progress finish:finish timeKey:timeKey];
}

- (void)countdown:(NSTimeInterval)time updateTime:(double)updateTime progress:(progressCall)progress finish:(finishCall)finish timeKey:(NSString *)timeKey {
    
    __block double timeout = time;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_barrier_async(self.queue, ^{
        dispatch_source_t timer = [self.timerDictionary objectForKey:timeKey];
//        NSLog(@"timeKey%@",timeKey);
        if (!timer) {
            timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
            [self.timerDictionary setObject:timer forKey:timeKey];
            dispatch_resume(timer);
//            NSLog(@"创建保存timeKey%@",timeKey);

        }
        dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), updateTime * NSEC_PER_SEC, 0);
        dispatch_source_set_event_handler(timer, ^{
            if (timeout <= 0) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.timerDictionary removeObjectForKey:timeKey];
                    dispatch_source_cancel(timer);
                    finish(timeKey);
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    progress(timeout);
                    timeout -= updateTime;
//                    NSLog(@"timeKey:%@-time%f",timeKey,timeout);
                });
            }
        });
        
    });
}

- (void)cancelTimer:(NSString *)timeKey {
    dispatch_barrier_async(self.queue, ^{
        dispatch_source_t timer = [self.timerDictionary objectForKey:timeKey];

        if (!timer) {
            return;
        }

        [self.timerDictionary removeObjectForKey:timeKey];
        dispatch_source_cancel(timer);
    });
}
- (void)checkExistTimer:(NSString *)timerName completion:(void (^)(BOOL))completion {
    dispatch_async(self.queue, ^{
        if ([self.timerDictionary objectForKey:timerName]) {
            completion(YES);
        } else {
            completion(NO);
        }
    });
}
//
/**
 *  传入一个时间,返回一个NSString格式为"00:00:00"的时间text
 *
 *  @param time 传入的时间值
 *
 *  @return 格式为"00:00:00"的时间text
 */
- (NSString *)createTimeStingWithTime:(NSTimeInterval)time {
    int hours = (int) time / 3600;
    int minutes = ((int) time - hours * 3600) / 60;
    int seconds = (int) time % 60;

    NSString *hou = [NSString stringWithFormat:@"%d", hours];
    NSString *min = [NSString stringWithFormat:@"%d", minutes];
    NSString *sec = [NSString stringWithFormat:@"%d", seconds];
    if (hours < 10) {
        hou = [NSString stringWithFormat:@"0%d", hours];
    }
    if (minutes < 10) {
        min = [NSString stringWithFormat:@"0%d", minutes];
    }
    if (seconds < 10) {
        sec = [NSString stringWithFormat:@"0%d", seconds];
    }
    if (time < 0) {
        return [NSString stringWithFormat:@"%@:%@:%@", @"00", @"00", @"00"];;
    } else {
        return [NSString stringWithFormat:@"%@:%@:%@", hou, min, sec];
    }
}


- (NSString *)createMMSS:(NSTimeInterval)time {
    int minutes = ((int) time) / 60;
    int seconds = (int) time % 60;

    NSString *min = [NSString stringWithFormat:@"%d", minutes];
    NSString *sec = [NSString stringWithFormat:@"%d", seconds];

    if (minutes < 10) {
        min = [NSString stringWithFormat:@"0%d", minutes];
    }

    if (seconds < 10) {
        sec = [NSString stringWithFormat:@"0%d", seconds];
    }

    if (time < 0) {//传入的时间小于0
        return [NSString stringWithFormat:@"%@:%@", @"00", @"00"];
    } else {
        return [NSString stringWithFormat:@"%@:%@", min, sec];
    }
}

@end
